import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

// 导入组件
// import Login from '../views/Login/Login.vue'
// import Reg from '../views/Reg/Reg.vue'
// import Main from '@/views/Main/Main.vue'
// import Home from '@/views/Menus/Home/Home.vue'
// import UserInfo from '@/views/Menus/User/UserInfo.vue'
// import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
// import UserPwd from '@/views/Menus/User/UserPwd.vue'
// import ArtCate from '@/views/Menus/Article/ArtCate.vue'
// import ArtList from '@/views/Menus/Article/ArtList.vue'

// 路由懒加载
const Login = () => import('../views/Login/Login.vue')
const Reg = () => import('../views/Reg/Reg.vue')
const Main = () => import('@/views/Main/Main.vue')
const Home = () => import('@/views/Menus/Home/Home.vue')
const UserInfo = () => import('@/views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const ArtCate = () => import('@/views/Menus/Article/ArtCate.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置导航守卫
// to: 到哪里去
// from: 从哪里来
// next: 是否放行
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 判断用户是否登录, 如果没登录跳转至 /login
  // 如果没有 token 就是没有登录
  // 智囊团: 如果没登录跳转至 /login, 在注册页或登录页就不用跳转到登录页
  // 紫阳: 没登录并且要去的页面不是登录或注册
  // 要去的页面既不是登录且不是注册
  // 写完后的效果: 如果我没有登录, 就只能去登录或注册页, 可以将登录注册页叫白名单
  // if (!token && to.path !== '/login' && to.path !== '/reg') {

  // 高级
  const whiteList = ['/login', '/reg']
  if (!token && !whiteList.includes(to.path)) {
    // 提醒用户未登录
    // alert('您未登录')
    // 用户体验更好的 $message
    Vue.prototype.$message.error('您还没登录呀傻子!')
    return next('/login')
  }
  next()
})

export default router
